<template>
  <div class="projectCreate">
    <el-tabs type="border-card">
      <el-tab-pane>
        <span slot="label">
          <i class="el-icon-date"></i> 基本信息
        </span>
        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="12">
            <el-radio-group v-model="radioMisstionType" size="small" @change="misstionChange">
              <el-radio :label="false" border>临时任务</el-radio>
              <el-radio :label="true" border>计划任务</el-radio>
            </el-radio-group>
          </el-col>
          <el-col :span="4">
            <el-button ref="btnCreate" :disabled="btnState" @click="CreateOrSaveProject(3)">立项下达</el-button>
          </el-col>
          <el-col :span="4">
            <el-button ref="btnCreate" :disabled="btnState" @click="CreateOrSaveProject(0)">保存</el-button>
          </el-col>
        </el-row>
        <div>监测类型</div>
        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="4">
            <!-- <CascaderProject @projectChange="projectChange"/> -->
            <CasCaderMonType @handleChange="projectChange" :options="monTypeCascader"/>
          </el-col>
        </el-row>

        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="4">
            <span>任务名称</span>
            <el-input placeholder="任务名称" maxlength="20" clearable v-model="misstionName"></el-input>
          </el-col>
          <el-col :span="4">
            <span>合同编号</span>
            <el-input placeholder="合同编号" maxlength="20" clearable v-model="contractNo"></el-input>
          </el-col>
        </el-row>

        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="6">
            <el-collapse>
              <el-collapse-item>
                <template slot="title">
                  委托单位
                  <i class="header-icon el-icon-info"></i>
                  {{detail1.Name}}
                </template>
                <el-autocomplete
                  value-key="Name"
                  :fetch-suggestions="querySearch"
                  placeholder="单位名称"
                  @select="enterpriseSelect1"
                  v-model="detail1.Name"
                ></el-autocomplete>
                <el-input placeholder="电话" maxlength="11" clearable v-model="detail1.PhoneNum"></el-input>
                <el-input placeholder="联系人" maxlength="20" clearable v-model="detail1.LegalName"></el-input>
                <el-input
                  placeholder="联系地址"
                  maxlength="11"
                  clearable
                  v-model="detail1.DetailAddress"
                ></el-input>
              </el-collapse-item>
              <el-collapse-item v-if="isEnvQualifyMon">
                <template slot="title">
                  监测单位
                  <i class="header-icon el-icon-info"></i>
                  {{detail2.Name}}
                </template>
                <el-autocomplete
                  value-key="Name"
                  :fetch-suggestions="querySearch"
                  placeholder="单位名称"
                  @select="enterpriseSelect2"
                  v-model="detail2.Name"
                ></el-autocomplete>
                <el-input placeholder="电话" maxlength="11" clearable v-model="detail2.PhoneNum"></el-input>
                <el-input placeholder="联系人" maxlength="20" clearable v-model="detail2.LegalName"></el-input>
                <el-input
                  placeholder="联系地址"
                  maxlength="11"
                  clearable
                  v-model="detail2.DetailAddress"
                ></el-input>
              </el-collapse-item>
            </el-collapse>
          </el-col>
        </el-row>

        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="4">
            <span>紧急程度</span>
            <el-rate
              v-model="rateEmergency"
              :colors="['#67C23A', '#E6A23C', '#F56C6C']"
              :low-threshold="1"
              :high-threshold="3"
              :max="3"
            ></el-rate>
          </el-col>
          <el-col :span="4">
            <span>是否评价</span>
            <el-switch v-model="isReview" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </el-col>
          <el-col :span="4">
            <span>是否送样检测</span>
            <el-switch v-model="isDelivery" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </el-col>
          <el-col :span="4">
            <span>是否允许采样人员变更立项</span>
            <el-switch v-model="isChangeProject" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </el-col>
        </el-row>

        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="4">
            <span class="demonstration">开始时间</span>
            <!-- <el-date-picker
              v-model="dateValue1"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions1"
              format="yyyy 年 MM 月 dd 日">
            ></el-date-picker>-->
            <el-date-picker
              v-model="dateValue1"
              :picker-options="pickerOptions1"
              type="date"
              placeholder="选择日期"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-col>
          <el-col :span="4">
            <span class="demonstration">结束时间</span>
            <el-date-picker
              v-model="dateValue2"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions1"
              @change="datePickerChange"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-col>
        </el-row>

        <!-- <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="4">
            <CascaderMonitem @handleChange="monitemChange"/>
          </el-col>
        </el-row>-->
        <!-- 正常任务 -->
        <MonitemTable v-if="!radioMisstionType" :tableData1="tableData"/>
        <!-- 周期任务 -->
        <div v-if="radioMisstionType">
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              快捷选择方式
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="month">月度</el-dropdown-item>
              <el-dropdown-item command="session">季度</el-dropdown-item>
              <el-dropdown-item command="year">年度</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            style="width:6%"
          ></el-input>

          <!-- @blur="handleInputConfirm" -->
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 标签</el-button>

          <el-tabs v-model="activeName2" closable @tab-remove="removeTab">
            <el-tab-pane
              v-for="(item,index) in cycleTags"
              :label="item.name"
              :name="item.name"
              :key="item.name"
            >
              {{index}}
              <MonitemTable :tableData1="item.tableData"/>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-tab-pane>
      <el-tab-pane label="评价标准">评价标准</el-tab-pane>
      <el-tab-pane label="费用核算">费用核算</el-tab-pane>
      <el-tab-pane label="业务合同">业务合同</el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
// import UnitAutoSelect from '@/components/input/autoinput.vue'
import CasCaderMonType from '@/components/input/cascader.vue'
import MonitemTable from '@/components/table/projectTable.vue'
export default {
  components: {
    // UnitAutoSelect,
    CasCaderMonType,
    MonitemTable
  },
  data () {
    return {
      test: [],
      btnState: false,
      monTypeCascader: [],
      inputVisible: false,
      inputValue: '',
      cycleTags: [
        {
          name: '前期',
          tableData: []
        },
        {
          name: '中期',
          tableData: []
        }
      ],
      tableData: [],
      activeName2: '1',
      misstionName: '', // 任务名称1
      contractNo: '', // 合同编号1
      radioMisstionType: true, // 临时任务Or计划任务1
      monitorType: [], // 监测类型1 大类 + 小类
      detail1: {
        // 1 委托单位
        Name: '',
        PhoneNum: '',
        LegalName: '',
        DetailAddress: ''
      },
      detail2: {
        // 1 被监测单位
        Name: '',
        PhoneNum: '',
        LegalName: '',
        DetailAddress: ''
      },
      rateEmergency: 1, // 1紧急程度
      isReview: true, // 1是否评价
      isChangeProject: false, // 1是否允许采样人员变更立项
      isDelivery: false, // 1是否送样评价
      isEnvQualifyMon: true,
      dateValue1: '', // 1开始时间
      dateValue2: '', // 1结束时间

      EnterPriseList: [
        {
          Name: 'XXX化工厂',
          PhoneNum: '13111112222',
          LegalName: '王五',
          DetailAddress: '长宁区新渔路144号'
        }
      ],
      options: [{}],
      pickerOptions1: {
        disabledDate (time) {
          return time.getTime() < Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      }
    }
  },

  methods: {
    enterpriseSelect1 (item) {
      this.detail1.Name = item.Name
      this.detail1.PhoneNum = item.PhoneNum
      this.detail1.DetailAddress = item.DetailAddress
      this.detail1.LegalName = item.LegalName
    },
    enterpriseSelect2 (value2) {
      this.detail2.Name = value2.Name
      this.detail2.PhoneNum = value2.PhoneNum
      this.detail2.DetailAddress = value2.DetailAddress
      this.detail2.LegalName = value2.LegalName
    },
    misstionChange (value3) {
      // if(value == 1)
      // {
      //     this.isEnvQualifyMon = false
      // }
      // else{
      //     this.isEnvQualifyMon = true
      // }
    },
    projectChange (value) {
      this.monitorType.push(value[0])
      this.monitorType.push(value[1])
      if (
        value != null &&
        value[0].toUpperCase() === '78640769-B667-4DF1-B3C7-C364446B7415'
      ) {
        this.isEnvQualifyMon = false
      } else {
        this.isEnvQualifyMon = true
      }
    },
    datePickerChange (value) {
      if (value < this.dateValue1) {
        this.$message('the end time was not more than start time')
        this.dateValue2 = ''
      }
    },
    monitemChange (value) {
      console.log('监测要素更改 清除后面监测点位和监测项目', value)
    },
    handleCommand (command) {
      if (command === 'month') {
        this.cycleTags.splice(0, this.cycleTags.length)
        for (var i = 1; i < 13; i++) {
          this.cycleTags.push({
            name: `${i}月`,
            tableData: []
          })
        }
      } else if (command === 'session') {
        this.cycleTags.splice(0, this.cycleTags.length)
        for (var i = 1; i < 5; i++) {
          this.cycleTags.push({
            name: `${i}季度`,
            tableData: []
          })
        }
      } else if (command === 'year') {
        this.cycleTags.splice(0, this.cycleTags.length)
        this.cycleTags.push({
          name: '年度',
          tableData: []
        })
      }

      this.$message('快捷周期选择 ' + command)
      // 根据不同确定tab 和 tableData的数据 month year session
    },
    handleClose (tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    querySearch (queryString, cb) {
      var EnterPriseList = this.EnterPriseList
      var results = queryString
        ? EnterPriseList.filter(this.createFilter(queryString))
        : EnterPriseList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter (queryString) {
      return restaurant => {
        return (
          restaurant.Name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        )
      }
    },
    handleInputConfirm () {
      let inputValue = this.inputValue
      if (
        inputValue !== '' &&
        this.cycleTags.filter(item => item.name === inputValue).length === 0
      ) {
        this.cycleTags.push({
          name: inputValue,
          tableData: []
        })
        console.log('push success')
      } else {
        this.$message('Tag名字重复')
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    removeTab (targetName) {
      this.cycleTags.forEach(e =>
        targetName === e.name // ? delete this.cycleTags[this.cycleTags.indexOf(e)]
          ? this.cycleTags.splice(this.cycleTags.indexOf(e), 1)
          : ''
      )
      // this.cycleTags.splice()
      // this.cycleTags.splice(index, 1)
    },
    // 以下是加载数据
    loadEnterPriseData () {
      // PhoneNum 电话 DetailAddress 联系地址
      // 单位名称 Name LegalName 联系人（法人名）
      // this.EnterPriseList
      this.axios.get('/Project/GetAllEnterPriseData').then(response => {
        // response.data.forEach(e => e.push({ value: 'ad' }))
        this.EnterPriseList = response.data
        // response.data.forEach(e=>this.EnterPriseList.push(e))
      })
    },
    loadMonTypeCascaderData () {
      this.axios.get('/Project/GetMonTypeCascader').then(response => {
        this.monTypeCascader = response.data
      })
    },
    CreateOrSaveProject (status) {
      // Save 和 Create状态不一样而已
      // this.btnState = true

      var data = {
        IsCycleMission: this.radioMisstionType,
        MissionTagName: '临时任务',
        Status: status,
        // 监测类型
        MonTypeBigId: this.monitorType[0],
        MonTypeSmallId: this.monitorType[1],
        // 任务名称
        Name: this.misstionName,
        // 合同编号
        ContactCode: this.contractNo,
        // 委托单位
        ClientId: this.detail1.id,
        ClientName: this.detail1.Name,
        ClientContratName: this.detail1.LegalName,
        ClientContactNumber: this.detail1.PhoneNum,
        ClientAddr: this.detail1.DetailAddress,
        // 监测单位
        RcvId: this.detail2.id,
        RcvName: this.detail2.Name,
        RcvContactName: this.detail2.LegalName,
        RcvContactNumber: this.detail2.PhoneNum,
        RcvAddr: this.detail2.DetailAddress,
        // 紧急程度
        Urgency: this.rateEmergency,
        // 是否评价
        IsEvaluate: this.isReview,
        // 是否送样监测
        IsSendSample: this.isDelivery,
        // 是否允许采样人员变更立项
        CanSamplingEidt: this.isChangeProject,
        // 开始时间
        StartDate: this.dateValue1,
        // 结束时间
        EndDate: this.dateValue2,
        // 具体监测项目Array-> 监测天数 监测频次 监测点位【Array（id，name）】    监测项目【Array （MonitemId,MonName,MethodName,MethodId,isout,hasQualify）】
        monProgramDetails: [] // 正常任务
      }

      var SendingData = []
      if (!this.radioMisstionType) {
        // 如果是临时任务
        data.monProgramDetails = this.tableData
        SendingData.push(data)
      } else {
        // 如果是周期任务
        // for(let i=0;this.cycleTags.length>i;i++){
        //   // var tempData = {}
        //   var tempData = JSON.parse(JSON.stringify(data))
        //   tempData.MissionTagName = this.cycleTags[i].name
        //   tempData.monProgramDetails = this.cycleTags[i].tableData
        //   // console.log('asdasd'+tempData.MissionTagName)
        //   // SendingData.push(tempData)
        //   this.test.push(tempData)
        //   console.log(`第${i+1}个 数据${this.test[i].MissionTagName}`)
        // }
        this.cycleTags.forEach(e => {
          var tempData = JSON.parse(JSON.stringify(data))
          tempData.MissionTagName = e.name
          tempData.monProgramDetails = e.tableData
          console.log('asdasd' + tempData.MissionTagName)
          SendingData.push(tempData)
          // this.test.push(tempData)
        })
      }
      this.axios
        .post('/Project/CreateProject', SendingData)
        .then(response => {
          this.btnState = false
          // 页面跳转
        })
        .catch(error => {})
    }
  },
  mounted () {
    // 需要在页面被渲染之前 加载的数据
    // this.loadEnterPriseData()
    this.loadMonTypeCascaderData()
  },
  created () {
    this.loadEnterPriseData()
  }
}
</script>

<style lang="stylus">
.el-row
  margin-bottom 20px
  &:last-child
    margin-bottom 0
.el-col
  border-radius 4px
.el-autocomplete
  width 100%
</style>
